package com.yanqu.road.server.cmd.activity.jieshi;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.jieshi.config.JieShiConfig;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.JieShiProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.jieshi.JieShiMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;

@Cmd(code = Protocol.S_JIESHI_VISIT_OTHER, desc = "拜访他人街市")
public class JieShiVisitOtherCmd extends AbstractCommand {

    private long serverId;
    private long userId;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        JieShiProto.JieShiVisitOtherReqMsg reqMsg = JieShiProto.JieShiVisitOtherReqMsg.parseFrom(packet.getBytes());
        serverId = reqMsg.getServerId();
        userId = reqMsg.getUserId();
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        JieShiConfig config = JieShiMgr.getConfig();
        if (config == null) {
            ret =  GameErrorCode.E_JIESHI_CONFIG_NOT_FOUND;
            return;
        }
        ActivityInfo activityInfo = config.getActivityInfo();
        if (activityInfo == null) {
            ret = GameErrorCode.E_JIESHI_ACTIVITY_NOT_FOUND;
            return;
        }
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            ret = GameErrorCode.E_JIESHI_ACTIVITY_NOT_IN_TIME;
            return;
        }
        if (serverId == GameServer.getInstance().getServerId()) {
            // 本服拜访
            player.sendPacket(Protocol.U_JIESHI_VISIT_OTHER, JieShiMgr.visitOther(userId));
        } else {
            // 跨服拜访
            JieShiProto.CrossJieShiVisitOtherReqMsg.Builder builder = JieShiProto.CrossJieShiVisitOtherReqMsg.newBuilder();
            builder.setActivityId(config.getActivityInfo().getActivityId());
            builder.setUserId(userId);
            builder.setServerId(serverId);
            player.sendPacket(CrossProtocol.C_CROSS_VISIT_OTHER_JIE_SHI, builder);
        }
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            JieShiProto.JieShiVisitOtherRespMsg.Builder respMsg = JieShiProto.JieShiVisitOtherRespMsg.newBuilder();
            respMsg.setRet(ret);
            player.sendPacket(Protocol.U_JIESHI_VISIT_OTHER, respMsg);
        }
    }
}
